/*
 * Copyright (C) 2010 恒康信息科技有限公司
 * 版权所有
 */
package com.jjmmbb.db.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

import com.jjmmbb.db.pojo.Item;

/**
 * dao类,实现基本的数据库操作<br/>
 * 需要保存到数据库中的对象的属性不能使用基本类型,建议只使用Integer 和 String<br/>
 * BaseItem做为通用对象,从demo创建只要修改tableName即可
 * 
 * @author yizhe
 * @date 2012-5-18
 */
public class ItemDao extends DBHelper {
	public static String tableName = "daiban"; // 从demo新建的dao类只需要修改这个地方,和BaseItem
	ContentValues contentValues = null;

	public ItemDao(Context context, String name, CursorFactory cursorFactory,
			int version) {
		super(context, name, cursorFactory, version);
	}

	public ItemDao(Context context) {
		super(context);
	}

	// pojo的整数都需要使用Long类型 或者Integer类型 建议使用Long
	public void iniContentValues(Item pojo) {
		contentValues = new ContentValues();
		// 修改数据库,增加字段,必须修改这里(不用类反射时)
		contentValues.put("id", pojo.id);
		contentValues.put("title", pojo.title);
		contentValues.put("team", pojo.team);
		contentValues.put("time", pojo.time);
		contentValues.put("timeAlarm", pojo.timeAlarm);
		contentValues.put("timeFinish", pojo.timeFinish);
		contentValues.put("timePlanComplete", pojo.timePlanComplete);
		contentValues.put("type", pojo.type);
		contentValues.put("typeAlarm", pojo.typeAlarm);
	}

	/**
	 * 添加数据,自动插入id
	 * 
	 * @return the row ID of the newly inserted row, or -1 if an error occurred
	 */
	public long insert(Item pojo) {
		SQLiteDatabase db = getWritableDatabase();// 获取可写SQLiteDatabase对象
		iniContentValues(pojo); // ContentValues类似map，存入的是键值对
		long result = db.insert(tableName, null, contentValues);
		return result;
	}

	/**
	 * 根据id删除记录
	 * 
	 * @param id
	 * @return the number of rows affected if a whereClause is passed in, 0
	 *         otherwise. To remove all rows and get a count pass "1" as the
	 *         whereClause.
	 */

	public int delete(int id) {
		SQLiteDatabase db = getWritableDatabase();
		int result = db.delete(tableName, "id=?", new String[] { id + "" });
		return result;
	}

	/**
	 * 根据ID更新记录的，跟插入的很像
	 * 
	 * @return the number of rows affected
	 * 
	 */
	public int update(Item pojo) {
		SQLiteDatabase db = getWritableDatabase();
		iniContentValues(pojo); // 初始化键值对
		int result = db.update(tableName, contentValues, "id=?",
				new String[] { pojo.id + "" });
		return result;
	}

	/**
	 * 查询所有数据
	 * 
	 * @return A {@link Cursor} object, which is positioned before the first
	 *         entry
	 */
	public Cursor select() {
		SQLiteDatabase db = getReadableDatabase();
		String sql = "select * from " + tableName;
		Cursor result = db.rawQuery(sql, new String[] {});
		return result;
	}

}
